#!/usr/bin/env python3

import os
import sys
import subprocess
import importlib

def check_dependencies():
    required_packages = ['numpy', 'torch', 'matplotlib', 'json']
    missing_packages = []
    
    for package in required_packages:
        try:
            if package == 'json':
                import json
            else:
                importlib.import_module(package)
            print(f"✓ {package}")
        except ImportError:
            missing_packages.append(package)
            print(f"✗ {package}")
    
    if missing_packages:
        print(f"\nMissing packages: {missing_packages}")
        print("Run: pip install " + " ".join(missing_packages))
        return False
    return True

def setup_directories():
    directories = [
        'inverse_barrier/data',
        'inverse_barrier/data/outputs_cylinder'
    ]
    
    for directory in directories:
        if not os.path.exists(directory):
            os.makedirs(directory)
            print(f"Created: {directory}")
        else:
            print(f"Exists: {directory}")

def run_tests():
    print("\n" + "="*50)
    print("Running tests...")
    print("="*50)
    
    try:
        sys.path.append('inverse_barrier')
        from utils_cylinder import create_cylinder_drum
        
        cylinder = create_cylinder_drum(0.05, 0.055, 0.03, 0.002)
        print(f"✓ Cylinder geometry OK, particles: {len(cylinder)}")
        
        import json
        with open('inverse_barrier/config_cylinder.json', 'r') as f:
            config = json.load(f)
        print("✓ Config file OK")
        
        return True
        
    except Exception as e:
        print(f"✗ Test failed: {e}")
        return False

def run_main_demo():
    print("\n" + "="*50)
    print("Starting demo...")
    print("="*50)
    
    try:
        sys.path.append('inverse_barrier')
        from simple_cylinder_demo import main
        
        main()
        return True
        
    except Exception as e:
        print(f"Demo failed: {e}")
        import traceback
        traceback.print_exc()
        return False

def main():
    print("Cylinder demo launcher")
    print("="*50)
    
    print("1. Checking dependencies...")
    if not check_dependencies():
        print("Install missing packages and try again")
        return
    
    print("\n2. Setting up directories...")
    setup_directories()
    
    print("\n3. Running tests...")
    if not run_tests():
        print("Tests failed")
        return
    
    print("\n4. Running demo...")
    if run_main_demo():
        print("\n" + "="*50)
        print("Demo completed!")
        print("Check inverse_barrier/data/outputs_cylinder/ for results")
        print("="*50)
    else:
        print("Demo failed")

if __name__ == "__main__":
    main() 